#include <REGX52.H>
#include "Delay.h"
#include "DS18B20.h"
#include "Key.h"
#include "LCD1602.h"
#include "AT24C02.h"
#include "Buzzer.h"
#include "Timer0.h"



float T,TShow;			//接收温度，显示温度
char TLow,THigh;		//设定温度阈值
unsigned char KeyNum;	//获取按键

void main()
{
	DS18B20_ConvertT();	//上电先转换一次温度，防止第一次读数据错误
	Delay(1000);	//等待转换完全
	
	THigh = AT24C02_ReadByte(0);	//读取
	TLow = AT24C02_ReadByte(1);		//数据
	
	if (THigh>125 || TLow<-55 || THigh < TLow)	//判断数据是否合法
	{
		THigh = 20;	//设置
		TLow = 15;	//默认值
	}
		
	LCD_Init(); 	//LCD初始化
	Timer0_Init();	//定时器0初始化
	
	LCD_ShowString(2,1,"TH:");		//'显'
	LCD_ShowString(2,9,"TL:");		//'示'
	LCD_ShowString(1,1,"T:");		//
	LCD_ShowSignedNum(2,4,THigh,3);	//'界'
	LCD_ShowSignedNum(2,12,TLow,3);	//'面'

	while(1)
	{
		KeyNum = Key();	//获取按键

		/*******温度读取及显示*****************************************/
		
		DS18B20_ConvertT();		//温度转换
		T = DS18B20_ReadT();	//接收温度
		
		/*控制符号显示*/
		if (T < 0)
		{
			LCD_ShowChar(1,4,'-');
			TShow = -T;		//转换为正数，方便后续处理
		}
		else
		{
			LCD_ShowChar(1,4,'+');
			TShow = T;		//得到温度
		}
		
		/*显示温度*/
		LCD_ShowNum(1,5,TShow,3);			//强制转换为无符号整形，自动丢失小数位
		LCD_ShowChar(1,8,'.');				//显示小数点
		LCD_ShowNum(1,10,(unsigned int)(TShow*100)%100,2);	//显示小数位的4位（对浮点数不能取余）
	
		
		/********阈值判断及显示****************************************/

		/*高低温调整*/
		if (KeyNum)		//判断按键是否按下，减少扫描时间
		{
			if (1 == KeyNum)	//高温加一
			{
				THigh++;
				if (THigh > 125) { THigh = 125; }	//防止高温大于最大值
			}
			if (2 == KeyNum)	//高温减一
			{
				THigh--;
				if (THigh <= TLow) { THigh++; } 	//防止高温小于低温
			}
			if (3 == KeyNum)	//低温加一
			{
				TLow++;
				if (TLow >= THigh) { TLow--; }		//防止低温大于高温
			}
			if (4 == KeyNum)	//低温减一
			{
				TLow--;
				if (TLow < -55) { TLow = -55; }		//防止低温小于最小值
			}
			LCD_ShowSignedNum(2,4,THigh,3);	//更新
			LCD_ShowSignedNum(2,12,TLow,3);	//显示
			
			AT24C02_WriteByte(0,THigh);	//‘存’
			Delay(5);					//‘储’
			AT24C02_WriteByte(1,TLow);	//‘数’
			Delay(5);					//‘据’
		}		
		/*报警判断*/
		if (T > THigh)
		{
			LCD_ShowString(1,13,"OV:H");
		}
		else if (T < TLow)
		{
			LCD_ShowString(1,13,"OV:L");
		}
		else 
		{
			LCD_ShowString(1,13,"    ");
		}
		
		/*********************************************************/
		
	}
}


//应注意中断不能打断DS18C20的时序
void Timer0_Rountine() interrupt 1
{	
	static unsigned int T0Count = 0;
	TL0 = 0x66;		//设置定时初值
	TH0 = 0xFC;		//设置定时初值
	T0Count++;	
	if (T0Count >= 20)
	{
		T0Count = 0;
		Key_Loop();
	}
}


































